﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormAssignShift : FormBaseData
    {
        private Ctrl_General mCtrlGeneral;
        private DataSet mdsEmpAssignShift, mdsEmpAvilable;
        private SqlDataAdapter mdaEmpAssShiftUpdate;
        private CurrencyManager mCurrencyManagerEmpAva;

        public FormAssignShift()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Assign Shift Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where PS.ID_Shift = " + "'" + txtShiftID.Text.Trim() + "'"
                    + " and Convert(varchar(8), PS.Begin_Date, 112) <= Convert(varchar(8), Convert(Datetime, '" + dtpToDate.Value.ToString("yyyy/MM/dd") + "'), 112) "
                    + " and Convert(varchar(8), PS.End_Date, 112) >= Convert(varchar(8), Convert(Datetime, '" + dtpToDate.Value.ToString("yyyy/MM/dd") + "'), 112) "
                    + " and Convert(varchar(8), PS.Begin_Date, 112) <= Convert(varchar(8), Convert(Datetime, '" + dtpFromDate.Value.ToString("yyyy/MM/dd") + "'), 112) "
                    + " and Convert(varchar(8), PS.End_Date, 112) >= Convert(varchar(8), Convert(Datetime, '" + dtpFromDate.Value.ToString("yyyy/MM/dd") + "'), 112) "

                    + " Order By PS.ID_Emp ";

                string lCondiction1 = " ID_Shift = " + "'" + txtShiftID.Text.Trim() + "' "
                    + " and Convert(varchar(8), Begin_Date, 112) <= Convert(varchar(8), Convert(Datetime, '" + dtpToDate.Value.ToString("yyyy/MM/dd") + "'), 112) "
                    + " and Convert(varchar(8), End_Date, 112) >= Convert(varchar(8), Convert(Datetime, '" + dtpToDate.Value.ToString("yyyy/MM/dd") + "'), 112) "
                    + " and Convert(varchar(8), Begin_Date, 112) <= Convert(varchar(8), Convert(Datetime, '" + dtpFromDate.Value.ToString("yyyy/MM/dd") + "'), 112) "
                    + " and Convert(varchar(8), End_Date, 112) >= Convert(varchar(8), Convert(Datetime, '" + dtpFromDate.Value.ToString("yyyy/MM/dd") + "'), 112) "
                    + " Order By ID_Emp ";

                string ls_SQL = "Select PS.ID_Emp, PF.Emp_NameVN, PF.DOB, PS.ID_Shift, PS.Begin_Date, PS.End_Date, PS.Note, "
                    +"PS.CreatedUser, PS.UpdatedUser, PS.CreatedDate, PS.UpdatedDate "
                    + "From HRM_PersonnelShift PS inner join HRM_PersonalProfile PF on PS.ID_Emp = PF.ID_Emp "
                    + lCondiction;

                mdsEmpAssignShift = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelShift");
                mCtrlGeneral.GetDataWithCondition(out mdaEmpAssShiftUpdate, "HRM_PersonnelShift", lCondiction1);

                if (mdsEmpAssignShift == null) return;
                mdbg_EmpBelongShift.DataSource = mdsEmpAssignShift;
                mdbg_EmpBelongShift.DataMember = "HRM_PersonnelShift";

                mRowManager = (CurrencyManager)mdbg_EmpBelongShift.BindingContext[mdsEmpAssignShift, "HRM_PersonnelShift"];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);
                LoadDataEmpAvailable();
                base.LoadMasterData();
                btnAdd.Enabled = false;
                btnRemove.Enabled = false;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Assign Shift Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Ctrl_LOG.Print("Assign Shift form", "LoadData() method", "Error: " + ex.Message);
                Cursor = Cursors.Default;
            }
        }

        private void LoadDataEmpAvailable()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();
                string ls_buildCond = "";
                if (mdsEmpAssignShift != null && mdsEmpAssignShift.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in mdsEmpAssignShift.Tables[0].Rows)
                    {
                        if (dr.RowState == DataRowState.Deleted) continue;
                        if (ls_buildCond.Equals(""))
                            ls_buildCond = "'" + dr["ID_Emp"].ToString() + "'";
                        else
                            ls_buildCond += ", '" + dr["ID_Emp"].ToString() + "'";
                    }
                }

                if (ls_buildCond.Equals(""))
                    ls_buildCond = " Order By ID_Emp ";
                else
                    ls_buildCond = " Where ID_Emp not in ( " + ls_buildCond + " ) Order By ID_Emp ";

                string ls_SQL = "Select PF.ID_Emp, PF.Emp_NameVN, PF.DOB, D.Dept_Name, P.Position_Name "
                    + " From HRM_PersonalProfile PF left outer join HRM_Department D on PF.ID_Dept = D.ID_Dept "
                    + " left outer join HRM_Position P on PF.ID_Position = P.ID_Position "
                    + ls_buildCond;

                mdsEmpAvilable = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonalProfile");

                if (mdsEmpAvilable == null) return;
                mdbg_AvilableEmp.DataSource = mdsEmpAvilable;
                mdbg_AvilableEmp.DataMember = "HRM_PersonalProfile";

                mCurrencyManagerEmpAva = (CurrencyManager)mdbg_AvilableEmp.BindingContext[mdsEmpAvilable, "HRM_PersonalProfile"];
                mCurrencyManagerEmpAva.PositionChanged += new EventHandler(RowMaster_Changed);

                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load employee available . Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }

        public override void save()
        {
            try
            {
                if (mdsEmpAssignShift == null) return;
                mRowManager.EndCurrentEdit();
                if (!mdsEmpAssignShift.HasChanges())
                {
                    base.save();
                    btnAdd.Enabled = false;
                    btnRemove.Enabled = false;
                    return;
                }
                DataSet ldsHasChanged = mdsEmpAssignShift.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["CreatedDate"] = DateTime.Now;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedDate"] = DateTime.Now;
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                    }

                    if (dr["ID_Emp"].ToString().Equals(""))
                        dr["ID_Emp"] = DBNull.Value;
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaEmpAssShiftUpdate, ldsHasChanged, "HRM_PersonnelShift", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsEmpAssignShift.AcceptChanges();
                    int li_pos = 0;
                    if (GetCurrentAction() == MODES.MODIFY) li_pos = mRowManager.Position;
                    /*if(GetCurrentAction() == MODES.ADD)*/
                    LoadData();
                    if (li_pos > 0) mRowManager.Position = li_pos;
                    base.save();
                    btnAdd.Enabled = false;
                    btnRemove.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Cannot save'. Error: '" + ls_Error + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void cancel()
        {
            mdbg_EmpBelongShift.Focus();
            if (mdsEmpAssignShift == null) return;
            mRowManager.EndCurrentEdit();
            mdsEmpAssignShift.RejectChanges();
            base.cancel();
            btnAdd.Enabled = false;
            btnRemove.Enabled = false;
        }

        public override void add()
        {
            mdbg_EmpBelongShift.Focus();            
            base.add();
            btnAdd.Enabled = true;
            btnRemove.Enabled = true;
        }

        public override void modify()
        {
            base.modify();
            btnAdd.Enabled = true;
            btnRemove.Enabled = true;
        }

        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            DataSet ldsDelete = (DataSet)mdbg_EmpBelongShift.DataSource;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaEmpAssShiftUpdate, ldsDelete, "HRM_PersonnelShift", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete'. Error: '" + lsReturnMessage + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
            }
            base.post_delete();
            LoadDataEmpAvailable();
        }

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (mCurrencyManagerEmpAva == null || mCurrencyManagerEmpAva.Count <= 0) return;
            DataRow drEV = mdsEmpAvilable.Tables[0].Rows[mCurrencyManagerEmpAva.Position];
            DataRow dr = mdsEmpAssignShift.Tables[0].NewRow();
            dr["ID_Emp"] = drEV["ID_Emp"];
            dr["Emp_NameVN"] = drEV["Emp_NameVN"];
            dr["DOB"] = drEV["DOB"];
            dr["ID_Shift"] = txtShiftID.Text.Trim();
            dr["Begin_Date"] = dtpFromDate.Value;
            dr["End_Date"] = dtpToDate.Value;
            mdsEmpAssignShift.Tables[0].Rows.Add(dr);
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
           DataRow dr = mdsEmpAssignShift.Tables[0].Rows[mRowManager.Position];
           dr.Delete();
           LoadDataEmpAvailable();
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            LoadData();
        }
    }
}
